package de.velvettear.bruteforce.kernel;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import de.velvettear.bruteforce.util.Log;

public class Database { 

	private static boolean driverLoaded = false;	
	private static Connection connection = null;
	
	private static String HOSTNAME = null;
	private static String DATABASENAME = null;
	private static String USERNAME = null;
	private static String PASSWORD = null;
	
	public static void loadDriver() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			driverLoaded = true;
		} catch (Exception e) {
			driverLoaded = false;
			Log.error(e);
		}		
	}

	public static void setCredentials(String hostname, String username, String password) {
		HOSTNAME = hostname;
		DATABASENAME = Statics.NAME_APPLICATION.toLowerCase();
		USERNAME = username;
		PASSWORD = password;
	}
	
	public static void resetCredentials() {
		HOSTNAME = null;
		DATABASENAME = null;
		USERNAME = null;
		PASSWORD = null;
	}
	
	public static Connection connect() {
		return connect(HOSTNAME, DATABASENAME, USERNAME, PASSWORD);		
	}
	
	public static Connection connect(String hostname, String databasename, String username, String password) {		
		connection = null;
		
		if (!driverLoaded) {
			loadDriver();
		}
		
		try {
			String connectionString = "jdbc:mysql://" + hostname;
			if (databasename != null) {
				connectionString += "/" + databasename;
			}
			connectionString += "?" + "user=" + username + "&password=" + password;			
			
			connection = DriverManager.getConnection(connectionString);
		} catch (Exception e) {
			Log.error(e);
		}
		
		return connection;
	}
	
	public static void disconnect() {
		try {
			if (connection != null) {
				connection.close();
			}		
			connection = null;
		} catch(Exception e) {
			Log.error(e);
		}		
	}
	
	protected static boolean createSchema() {
		boolean created = false;
		try {
			connect(HOSTNAME, null, USERNAME, PASSWORD);
			
			Statement sqlStatement = connection.createStatement();
			
			created = sqlStatement.execute("CREATE DATABASE IF NOT EXISTS " + Statics.NAME_APPLICATION.toLowerCase() + "");
			
			disconnect();
		} catch (Exception e) {
			Log.error(e);
		}	
		return created;
	}
			
	public static ResultSet query(String statement) {
		ResultSet result = null;
		try {
			connect();
			
			Statement sqlStatement = connection.createStatement();
			
			result = sqlStatement.executeQuery(statement);
		} catch (Exception e) {
			Log.error(e);
		}
		return result;
	}
	
	public static boolean execute(String statement) {
		boolean executed = false;
		try {
			connect();
			
			Statement sqlStatement = connection.createStatement();
			
			executed = sqlStatement.execute(statement);
			
			disconnect();
		} catch (Exception e) {
			Log.error(e);
		}
		return executed;
	}
	
}
